package aggregation

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/aggregation"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/aggregation"
)

type statisticsRepository struct {
}

// NewStatisticsRepository
// 统计管理
func NewStatisticsRepository() StatisticsRepositoryIface {
	return &statisticsRepository{}
}

func (r *statisticsRepository) Data(ctx context.Context, param *aggregation.DataParam) (*aggregation.StatisticsData, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	req := &pb.StatisticsDataRequest{}

	client := pb.NewStatisticsServiceClient(conn)
	response, err := client.StatisticsData(ctx, req)
	if err != nil {
		return nil, err
	}

	statisticsData := &aggregation.StatisticsData{
		ViewOpptyTotal:       response.ViewOpptyTotal,
		NewClueTotal:         response.NewClueTotal,
		NewCustomerTotal:     response.NewCustomerTotal,
		ContactCustomerTotal: response.ContactCustomerTotal,
		CustomerDynamicTotal: response.CustomerDynamicTotal,
	}
	return statisticsData, nil
}

// UseRankList 统计列表
func (r *statisticsRepository) UseRankList(ctx context.Context, param *aggregation.UseRankListParam) (*aggregation.UseRankListData, error) {
	if param == nil {
		return nil, errors.New("缺少参数")
	}

	req := &pb.UseRankListRequest{
		Type: param.Type,
	}

	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewStatisticsServiceClient(conn)
	response, err := client.UseRankList(ctx, req)
	if err != nil {
		return nil, err
	}

	useRankList := make([]*aggregation.UseRankItem, 0)
	for _, item := range response.List {
		beCopyItem := &aggregation.UseRankItem{
			Total:    item.Total,
			UserId:   item.UserId,
			UserName: item.UserName,
		}
		useRankList = append(useRankList, beCopyItem)
	}
	useRankListData := &aggregation.UseRankListData{}
	useRankListData.List = useRankList
	return useRankListData, nil
}
